package com.lcifn.middleware.rpc.server.handler;

import com.lcifn.middleware.rpc.spi.ServiceSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求handler注册器
 * @author lichao
 * @date 2021/2/1 16:51
 */
public class RequestHandlerRegistry {

    private static final Logger logger = LoggerFactory.getLogger(RequestHandlerRegistry.class);

    // handler类型Map
    private final Map<Integer, RequestHandler> handlerMap = new HashMap<>();
    // 单例实体
    private static RequestHandlerRegistry instance;

    /**
     * 获取单例实体
     * @return
     */
    public static synchronized RequestHandlerRegistry getInstance() {
        if (null == instance) {
            instance = new RequestHandlerRegistry();
        }
        return instance;
    }

    /**
     * 私有构造函数
     */
    private RequestHandlerRegistry () {
        List<RequestHandler> handlerList = ServiceSupport.loadAll(RequestHandler.class);
        for (RequestHandler handler : handlerList) {
            handlerMap.put(handler.type(), handler);
            logger.info("Load request handler, type: {}, class: {}.", handler.type(), handler.getClass().getCanonicalName());
        }
    }

    /**
     * 类型获取handler
     * @param type
     * @return
     */
    public RequestHandler get(int type) {
        return handlerMap.get(type);
    }
}
